<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Redis;

// 会员等级管理控制器
class MemberDiscountController extends Controller
{
    // 显示会员等级管理页
    public function MemberDisCountPage()
    {
        // 准备redis键名
        $discountkey = 'home_user_member_discount_data';

        // 查询redis是否有该用户
        $discount = Redis::hGetAll($discountkey);

        // 如果有就更改redis用户状态
        if ($discount) {
            // 如果有则返回视图层
            return view('Admin.member.member-discount', ['discount' => $discount]);
        } else {
            // 如果没有则创建
            Redis::hMSet($discountkey, [
                '1' => '100',
                '2' => '99',
                '3' => '98',
            ]);
            // 创建完取出
            $discount = Redis::hGetAll($discountkey);
            // 返回到视图层
            return view('Admin.member.member-discount', ['discount' => $discount]);
        }
    }

    /**
     * 折扣更改
     */
    public function DisCountChange(Request $request)
    {
        // 准备折扣
        $generalmember = intval($request->generalmember);
        $goldmember = intval($request->goldmember);
        $diamond = intval($request->diamond);

        // 准备redis键名
        $discountkey = 'home_user_member_discount_data';

        // 判断折扣是否小于95折
        if ($generalmember < 95) {
            return 500;
        }

        if ($goldmember < 95) {
            return 500;
        }

        if ($diamond < 95) {
            return 500;
        }

        // 判断是否非法折扣
        if ($generalmember > 100) {
            return 500;
        }

        if ($goldmember > 100) {
            return 500;
        }

        if ($diamond > 100) {
            return 500;
        }

        // 判断该表是否存在
        $discount = Redis::Exists($discountkey);

        // 不存在则创建
        if (!$discount) {
            Redis::hMSet($discountkey, [
                '1' => $generalmember,
                '2' => $goldmember,
                '3' => $diamond,
            ]);
            // 创建完取出
            $discount = Redis::hGetAll($discountkey);
            // 返回成功状态码
            return 200;
        }

        // 存在则删除重建
        Redis::del($discountkey);
        // 创建
        Redis::hMSet($discountkey, [
            '1' => $generalmember,
            '2' => $goldmember,
            '3' => $diamond,
        ]);
        // 创建完取出
        $discount = Redis::hGetAll($discountkey);
        // 返回成功状态码
        return 200;
    }

}
